package impl;

import dao.UserDao;
import domain.User;
import utils.JDBCutil;

import java.sql.Connection;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {
    @Override
    public boolean addUser(User loginUser) throws SQLException {
        Connection con = JDBCutil.getCon();
      /*定义sql语句*/
        String sql="insert into user(username,password) values(?,?)";
        String str[]={loginUser.getUsername(),loginUser.getPassword()};
        int result = JDBCutil.excuteupdate(sql,str);
       return result==1;
    }
    @Override
    public List<User> selectUser(User loginUser) throws SQLException {
        Connection con = JDBCutil.getCon();
        /*定义sql语句*/
        String sql = "select * from user where username=? and password=?";
//        PreparedStatement pst = con.prepareStatement(sql);
//
//        pst.setString(1,loginUser.getUsername());
//        pst.setString(2,loginUser.getPassword());
//        ResultSet rs = pst.executeQuery();
        String str[] = {loginUser.getUsername(),loginUser.getPassword()};
        ResultSet rs = JDBCutil.excuteQuery(sql, str);
        User user = null;
        List<User> list = new ArrayList<>();
        while(rs.next()){
            int id = rs.getInt("id");
            String username = rs.getString("username");
            String password = rs.getString("password");
            /*从数据库取出来，封装到 类 中*/
            user = new User(id,username,password);
    /*
    多个对象，存储
    * 存储单一数据 用变量
    * 存储成绩 用 数组
    *
    * 存储不同类型的数据  类
    * 如果存储对象  用 集合
    *
    * */
            list.add(user);
        }
        return list;
    }
}
